from requests import Response
from rest_framework import viewsets, permissions,status
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from apps.address.models import Address
from apps.address.serializers import AddressSerializer
from apps.orders.serializers import OrderSerializer
from apps.orders.models import Order
from django.db import models


class UserAddressViewSet(viewsets.ModelViewSet):
    serializer_class = AddressSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        return Address.objects.filter(user=self.request.user)

class UserOrderViewSet(viewsets.ReadOnlyModelViewSet):
    """获取当前用户的订单列表"""
    serializer_class = OrderSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        # 关联地址信息
        return Order.objects.filter(
            user=self.request.user
        ).select_related('address').order_by('-created_at')
    
class AddressViewSet(viewsets.ModelViewSet):
    """
    完整的地址管理视图集
    包含标准CRUD操作和自定义端点
    """
    serializer_class = AddressSerializer
    permission_classes = [permissions.IsAuthenticated]
    
    # 关键修复：明确设置queryset
    queryset = Address.objects.all()  # 设置非空查询集
    
    def get_queryset(self):
        """
        返回当前用户的地址列表
        按默认地址优先、最近修改排序
        """
        return self.queryset.filter(
            user=self.request.user
        ).order_by(
            '-is_default', 
            '-updated_at'
        ).select_related('user')
    
    def perform_create(self, serializer):
        """创建地址时自动关联用户并处理默认地址"""
        address = serializer.save(user=self.request.user)
        
        # 如果设置为默认地址，取消其他默认地址
        if address.is_default:
            self.get_queryset().exclude(id=address.id).update(is_default=False)
    
    @action(detail=False, methods=['post'], url_path='add-user-address')
    def add_user_address(self, request):
        """
        自定义添加地址端点
        POST /api/address/addresses/add-user-address/
        """
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        return Response(
            serializer.data,
            status=status.HTTP_201_CREATED
        )
    
    @action(detail=True, methods=['patch'], url_path='set-default')
    def set_default_address(self, request, pk=None):
        """
        设置默认地址
        PATCH /api/address/addresses/<pk>/set-default/
        """
        address = self.get_object()
        with transaction.atomic():
            # 先取消所有默认地址
            self.get_queryset().update(is_default=False)
            # 再设置当前地址为默认
            address.is_default = True
            address.save()
        return Response({'status': 'default address set'})